import { component$ } from '@builder.io/qwik';
import { Link, routeLoader$ } from '@builder.io/qwik-city';
import List, { ListHeader, ListItem } from '~/components/ui/List';
import { getUserId } from '~/server/authn';
import { db } from '~/server/db';
import { postService } from '~/server/service/post-service';

export const useLoader = routeLoader$(async (requestEvent) => {
  const userId = getUserId(requestEvent);
  const posts = await postService.findByUserId(db, userId, 20);
  return { posts };
});

export default component$(() => {
  const collectionSignal = useLoader();
  const { posts } = collectionSignal.value;
  return (
    <List>
      <ListHeader class="flex justify-between">最近文章</ListHeader>
      {posts.map((post) => (
        <ListItem key={post.id.toString()}>
          <Link href={`/posts/${post.id.toString()}`}>{post.title}</Link>
        </ListItem>
      ))}
    </List>
  );
});
